import 'package:get/get.dart';
import '../../../data/models/wiki_config.dart';
import '../../../data/models/browse_history.dart';

import '../../../data/repositories/wiki_repository.dart';
import '../../../utils/storage_service.dart';
import '../../../config/app_constants.dart';
import '../../../data/services/remote_config_service.dart';

class MainScreenController extends GetxController {
  final WikiRepository _wikiRepository = WikiRepository();
  final RemoteConfigService _remoteConfigService =
      Get.find<RemoteConfigService>();
  late StorageService _storageService;

  // 当前选中的底部导航栏索引
  final RxInt currentIndex = 0.obs;

  // 当前Wiki站点
  final Rx<WikiItem?> currentWikiSite = Rx<WikiItem?>(null);

  // 当前Wiki URL
  final RxString currentWikiUrl = AppConstants.defaultWikiUrl.obs;

  // 页面标题
  final RxString pageTitle = AppConstants.appName.obs;

  // Wiki配置
  final Rx<WikiConfig?> wikiConfig = Rx<WikiConfig?>(null);

  // 收藏列表
  final RxList<WikiItem> favorites = <WikiItem>[].obs;

  // 历史记录
  final RxList<BrowseHistory> history = <BrowseHistory>[].obs;

  @override
  void onInit() {
    super.onInit();
    _initializeStorage();
    _loadWikiConfig();
    _loadCurrentWiki();
    _loadFavorites();
    _loadHistory();
  }

  // 加载Wiki配置
  Future<void> _loadWikiConfig() async {
    try {
      final config = await _remoteConfigService.getWikiConfig();
      wikiConfig.value = config;
    } catch (e) {
      print('Error loading wiki config: $e');
    }
  }

  // 加载收藏列表
  Future<void> _loadFavorites() async {
    try {
      await _initializeStorage();
      final favoriteIds = _storageService.getFavorites();
      final config = wikiConfig.value;
      if (config != null) {
        final favoriteItems = config.wikis
            .where((item) => favoriteIds.contains(item.id))
            .toList();
        favorites.assignAll(favoriteItems);
      }
    } catch (e) {
      print('Error loading favorites: $e');
    }
  }

  // 加载历史记录
  Future<void> _loadHistory() async {
    try {
      await _initializeStorage();
      final historyData = _storageService.getHistory();
      // TODO: 将历史数据转换为WikiSearchResult
      // history.assignAll(historyData);
    } catch (e) {
      print('Error loading history: $e');
    }
  }

  // 初始化存储服务
  Future<void> _initializeStorage() async {
    _storageService = await StorageService.getInstance();
  }

  // 加载当前Wiki
  Future<void> _loadCurrentWiki() async {
    try {
      await _initializeStorage();

      // 从本地存储获取当前Wiki ID
      final currentWikiId = _storageService.getCurrentWikiId();

      // 根据ID获取Wiki站点信息
      final wikiSite = await _wikiRepository.getWikiSiteById(currentWikiId);

      if (wikiSite != null) {
        currentWikiSite.value = wikiSite;
        currentWikiUrl.value = wikiSite.url;
        pageTitle.value = wikiSite.name;
      } else {
        // 如果找不到Wiki站点，使用默认的
        await _setDefaultWiki();
      }
    } catch (e) {
      print('Error loading current wiki: $e');
      await _setDefaultWiki();
    }
  }

  // 设置默认Wiki
  Future<void> _setDefaultWiki() async {
    try {
      final defaultWiki =
          await _wikiRepository.getWikiSiteById(AppConstants.defaultWikiId);
      if (defaultWiki != null) {
        currentWikiSite.value = defaultWiki;
        currentWikiUrl.value = defaultWiki.url;
        pageTitle.value = defaultWiki.name;
        await _storageService.setCurrentWikiId(defaultWiki.id);
        await _storageService.setCurrentWikiUrl(defaultWiki.url);
      }
    } catch (e) {
      print('Error setting default wiki: $e');
      // 如果连默认Wiki都获取不到，使用硬编码的URL
      currentWikiUrl.value = AppConstants.defaultWikiUrl;
      pageTitle.value = '星露谷物语Wiki';
    }
  }

  // 切换底部导航栏
  void changeTabIndex(int index) {
    currentIndex.value = index;
    _updatePageTitle(index);
  }

  // 更新页面标题
  void _updatePageTitle(int index) {
    switch (index) {
      case 0:
        pageTitle.value = currentWikiSite.value?.name ?? '首页';
        break;
      case 1:
        pageTitle.value = '分类';
        break;
      case 2:
        pageTitle.value = '设置';
        break;
      default:
        pageTitle.value = AppConstants.appName;
    }
  }

  // 切换Wiki站点
  Future<void> switchWikiSite(WikiItem wikiSite) async {
    try {
      currentWikiSite.value = wikiSite;
      currentWikiUrl.value = wikiSite.url;

      // 保存到本地存储
      await _storageService.setCurrentWikiId(wikiSite.id);
      await _storageService.setCurrentWikiUrl(wikiSite.url);

      // 如果当前在首页，更新页面标题
      if (currentIndex.value == 0) {
        pageTitle.value = wikiSite.name;
      }

      // 切换到首页显示新的Wiki内容
      changeTabIndex(0);

      Get.snackbar(
        '切换成功',
        '已切换到 ${wikiSite.name}',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      print('Error switching wiki site: $e');
      Get.snackbar(
        '切换失败',
        '无法切换到 ${wikiSite.name}，请稍后重试',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 3),
      );
    }
  }

  // 刷新当前Wiki
  Future<void> refreshCurrentWiki() async {
    if (currentWikiSite.value != null) {
      currentWikiUrl.refresh();
    }
  }

  // 获取当前Wiki的搜索URL
  String getSearchUrl(String query) {
    if (currentWikiSite.value != null && query.isNotEmpty) {
      return '${currentWikiSite.value!.url}/search?q=${Uri.encodeComponent(query)}';
    }
    return currentWikiUrl.value;
  }

  // 检查是否为首页
  bool get isHomePage => currentIndex.value == 0;

  // 检查是否为分类页
  bool get isCategoryPage => currentIndex.value == 1;

  // 检查是否为设置页面
  bool get isSettingsPage => currentIndex.value == 2;

  // 添加到收藏
  Future<void> addToFavorites(WikiItem item) async {
    try {
      if (!favorites.any((fav) => fav.id == item.id)) {
        favorites.add(item);
        await _storageService.addToFavorites(item.id);

        Get.snackbar(
          '收藏成功',
          '已添加到收藏夹',
          snackPosition: SnackPosition.BOTTOM,
          duration: const Duration(seconds: 2),
        );
      }
    } catch (e) {
      print('Error adding to favorites: $e');
    }
  }

  // 从收藏中移除
  Future<void> removeFromFavorites(WikiItem item) async {
    try {
      favorites.removeWhere((fav) => fav.id == item.id);
      await _storageService.removeFromFavorites(item.id);

      Get.snackbar(
        '取消收藏',
        '已从收藏夹移除',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      print('Error removing from favorites: $e');
    }
  }

  // 检查是否已收藏
  bool isFavorite(WikiItem item) {
    return favorites.any((fav) => fav.id == item.id);
  }

  // 添加到历史记录
  Future<void> addToHistory(WikiSearchResult result) async {
    try {
      // 创建BrowseHistory对象
      final historyItem = BrowseHistory(
        wikiId: result.wiki.id,
        wikiName: result.wiki.name,
        wikiUrl: result.wiki.url,
        title: result.wiki.name,
        description: result.wiki.description,
        visitCount: 1,
        createdAt: DateTime.now(),
        lastVisitAt: DateTime.now(),
      );

      // 移除重复项
      history.removeWhere((item) => item.wikiUrl == result.wiki.url);

      // 添加到开头
      history.insert(0, historyItem);

      // 限制历史记录数量
      if (history.length > 100) {
        history.removeRange(100, history.length);
      }

      // 保存到本地存储
      // TODO: 实现历史记录的本地存储
    } catch (e) {
      print('Error adding to history: $e');
    }
  }

  // 清除历史记录
  Future<void> clearHistory() async {
    try {
      history.clear();
      // TODO: 清除本地存储的历史记录

      Get.snackbar(
        '清除成功',
        '历史记录已清空',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      print('Error clearing history: $e');
    }
  }
}
